package net.gaox.designs.behaviors.strategys.config;

import net.gaox.designs.behaviors.strategys.annotation.MsgTypeHandler;
import net.gaox.designs.behaviors.strategys.service.MessageService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * <p> 消息策略模式启动时加载Been监听事件 </p>
 *
 * @author gaox·Eric
 * @date 2020/2/25 14:57
 */
@Component
public class MessageServiceListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //获取Been，条件：带有MsgTypeHandler注解
        Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(MsgTypeHandler.class);
        //Been集合的类
        MessageServiceContext messageServiceContext = event.getApplicationContext().getBean(MessageServiceContext.class);
        beans.forEach((name, bean) -> {
            //获得注解
            MsgTypeHandler typeHandler = bean.getClass().getAnnotation(MsgTypeHandler.class);
            //调用putMessageService方法将消息类型和消息实现注入到messageServiceContext的Map中
            messageServiceContext.putMessageService(typeHandler.value().code, (MessageService) bean);
        });
    }
}